package com.liming.resource.core.biz;

import com.liming.core.util.config.CouchdbConfig;
import com.liming.resource.api.biz.IResourceService;
import com.liming.resource.api.persistence.IResourceBean;
import com.liming.resource.core.ResourceBeanImpl;
import org.lightcouch.CouchDbClient;
import org.lightcouch.Response;


import java.util.ArrayList;
import java.util.List;

/**
 * @类描述：IResourceService实现类
 * @创建人：wangkr
 * @创建时间：2014-04-03 下午5:16
 * @修改人：
 * @修改时间：
 * @修改备注：
 */

public class ResourceServiceImpl implements IResourceService {
    private static CouchDbClient dbClient;

    public void init() {
        CouchdbConfig.getCouchdbConfig().setDbName("dsa_resource");
        dbClient = new CouchDbClient(
                CouchdbConfig.getCouchdbConfig().getDbName(),
                true,
                "http",
                CouchdbConfig.getCouchdbConfig().getHost(),
                CouchdbConfig.getCouchdbConfig().getPort(),
                CouchdbConfig.getCouchdbConfig().getUsername(),
                CouchdbConfig.getCouchdbConfig().getPassword());
    }

    @Override
    public IResourceBean addResource(IResourceBean message) {
        Response response = dbClient.save(message);
        IResourceBean foo = dbClient.find(ResourceBeanImpl.class, response.getId());
        return foo;
    }
    @Override
    public IResourceBean updateResource(IResourceBean message) {
        Response response = dbClient.update(message);
        IResourceBean foo = dbClient.find(ResourceBeanImpl.class, response.getId());
        return foo;
    }
    @Override
    public void putResource(IResourceBean message){
        if(null != ((ResourceBeanImpl) message).getRevision()){
            updateResource(message);
        }else{
            addResource(message);
        }
    }

    @Override
    public IResourceBean findResource(String id) {
        IResourceBean foo = dbClient.find(ResourceBeanImpl.class, id);
        return foo;
    }
    @Override
    public void deleteResource(String id) {
        IResourceBean foo = dbClient.find(ResourceBeanImpl.class, id);
        dbClient.remove(foo);
    }
    @Override
    public List<IResourceBean> getAllResource() {
        List resourceList;
        try {
            resourceList = dbClient.view("_all_docs").includeDocs(true).query(ResourceBeanImpl.class);

        }catch (Exception e){
            return new ArrayList<IResourceBean>();
        }
        if(null != resourceList && resourceList.size() <= 0){
            return new ArrayList<IResourceBean>();
        }
        return resourceList;
    }
    @Override
    public void destroy() {
        dbClient.shutdown();
    }
}


